#!/bin/bash
#参数：ORACLE_HOME、节点hostname，DB_NAME|SID，
# TNSNames.ora
function SUDO_ORA_CMD() {
    USER=$1
    shift
    echo "Exec command: su - '$USER' -c '$@'"
    eval "su - '$USER' -c '$@'"
    exitCode=$?
    if [ $exitCode -ge 128 ]; then
        #负数返回码，大于127就是负数的补码
        echo "ERROR: Installation failed, exitCode:$exitCode."
        exit $exitCode
    elif [ $exitCode -gt 0 ]; then
        echo "WARN: Installation has some warning, exitCode:$exitCode."
    else
        echo "FINE: All installations were successful."
    fi
}

#参数处理,全部用长参数
######################################
function parseOpts() {
    OPT_SPEC=":h-:"
    while getopts "$OPT_SPEC" optchar; do
        case "${optchar}" in
        -)
            case "${OPTARG}" in
            CV_ASSUME_DISTID)
                CV_ASSUME_DISTID="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            ORACLE_USER)
                ORACLE_USER="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            *)
                if [ "$OPTERR" = 1 ] && [ "${OPT_SPEC:0:1}" != ":" ]; then
                    echo "Unknown option --${OPTARG}" >&2
                fi
                ;;
            esac
            ;;
        h)
            usage
            exit 2
            ;;
        *)
            if [ "$OPTERR" != 1 ] || [ "${OPT_SPEC:0:1}" = ":" ]; then
                echo "Non-option argument: '-${OPTARG}'" >&2
            fi
            ;;
        esac
    done
}

parseOpts "$@"

if [ -z "$ORACLE_USER" ]; then
    echo "ERROR: Must defined ORACLE_USER with option --ORACLE_USER."
    exit 2
fi

oraEnv=$(SUDO_ORA_CMD $ORACLE_USER env | grep ORACLE_)
echo "$oraEnv"
eval "$oraEnv"

ENV_DISTID=""
if [ "$CV_ASSUME_DISTID" != "AUTO" ]; then
    ENV_DISTID="CV_ASSUME_DISTID=$CV_ASSUME_DISTID"
fi

echo "Try to config oracle database listner..."
echo "----------------------------------------------"
SUDO_ORA_CMD $ORACLE_USER $ENV_DISTID ${ORACLE_HOME}/bin/netca -silent -responseFile $ORACLE_HOME/assistants/netca/netca.rsp

echo "Try to start oracle database listner..."
echo "----------------------------------------------"
SUDO_ORA_CMD $ORACLE_USER ${ORACLE_HOME}/bin/lsnrctl start
